﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JXT.PrimaryKey.Batman.Extensions;
using JXT.PrimaryKey.Batman.Core.Security;

namespace JXT.PrimaryKey.Batman.Core.OAuth
{
    /// <summary>
    /// OAuth认证扩展
    /// </summary>
    public static class OAuthExtensions
    {
        private static readonly string _defaultKey = Guid.NewGuid().ToString("N");

        /// <summary>
        /// 对token进行AES加密
        /// </summary>
        /// <param name="token">token</param>
        /// <param name="key">key</param>
        /// <returns>加密字符串</returns>
        public static string ToEncryptionString(this OAuthToken token, string key = null)
        {
            if (token == null)
                throw new ArgumentNullException("context");
            if (String.IsNullOrWhiteSpace(key))
                key = _defaultKey;
            return AesHelper.Encode(token.ToJsonString(), key);
        }

        /// <summary>
        /// 解密Token数据
        /// </summary>
        /// <param name="encryptionString">加密字符串</param>
        /// <param name="key">key</param>
        /// <returns>解密生成的OAuthToken对象</returns>
        public static OAuthToken ToDecryptAuthContext(this string encryptionString, string key = null)
        {
            if (String.IsNullOrWhiteSpace(encryptionString))
                throw new ArgumentNullException("encryptionString");
            if (String.IsNullOrWhiteSpace(key))
                key = _defaultKey;
            return AesHelper.Decode(encryptionString, key).ToJsonObject<OAuthToken>();
        }
    }
}
